from PIL import Image, ImageEnhance, ImageOps
import pytesseract
import os
import requests
import re
import time
# import subprocess

# 二值化算法
def binarizing(img,threshold):
    pixdata = img.load()
    w, h = img.size
    for y in range(h):
        for x in range(w):
            if pixdata[x, y] < threshold:
                pixdata[x, y] = 0
            else:
                pixdata[x, y] = 255
    return img


def get_screen():
    # pic = subprocess.Popen('adb shell screencap -p', shell=True, stdout=subprocess.PIPE)
    # screenshot = pic.stdout.read()
    # # screenshot = screenshot.replace(b'\r\n', b'\n')
    # # screenshot = screenshot.replace(b'\r\r\n', b'\n')
    # with open('screenshot.png', 'wb') as f:
    #     f.write(screenshot)
    os.system('adb shell screencap -p /sdcard/screenshot.png')
    os.system('adb pull /sdcard/screenshot.png .')

def start():
    get_screen()
    image = Image.open('./screenshot_spec.png')
    color1 = image.getpixel((615,349))
    # color2 = image.getpixel((768, 981))
    # print(color1)
    # print(color2)
    # # 出现计时条，并且为红色时
    # if color1 == (242, 89, 75, 255) and color2 == (255, 255, 255, 255):
    # return 1
    if color1 == (242, 89, 75, 255):
        return 1
    # if color2 == (255, 255, 255, 255):
    #     return 1
    else:
        return 0

def get_word():
    image = Image.open('./screenshot_spec.png')
    # 图片一分为二
    question = image.crop((18, 591, 1058, 865))
    choices = image.crop((250, 969, 829, 1684))
    # 图片增强
    question = ImageEnhance.Contrast(question).enhance(1.5)
    choices = ImageEnhance.Contrast(choices).enhance(1.5)
    # 转化为灰度图
    question = question.convert('L')
    choices = choices.convert('L')
    # 把图片变成二值图像
    question = binarizing(question, 190)
    choices = binarizing(choices, 190)
    # question图片颜色反转
    question = ImageOps.invert(question)
    # # 看一下处理后的图片是什么样
    # question.save('question.png')
    # choices.save('choices.png')
    # question图片转化文字
    tessdata_dir_config = '--tessdata-dir "C:\\Program Files (x86)\\Tesseract-OCR\\tessdata" --psm 6'
    text = pytesseract.image_to_string(question, lang='chi_sim', config=tessdata_dir_config)
    text = text.replace('\n', '')
    text = text.replace(' ', '')
    print(text)
    # choices图片转化文字
    text2 = pytesseract.image_to_string(choices, lang='chi_sim', config=tessdata_dir_config)
    text2 = text2.replace(' ','')
    p = re.compile(r'\n|\r|_|-|一')
    s = p.sub(' ', text2)
    text_list = s.split(' ')
    print(text_list)
    text_list.insert(0, text)
    return text_list


def baidu_question(question):
    # 百度查询问题，返回整理后的页面内容（字符串）
    kw = {'wd': question}
    headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36"}
    response = requests.get("http://www.baidu.com/s?", params=kw, headers=headers)
    response_content = response.text
    p = re.compile(r'<.*?>|".*?":".*?"|"http://.*?"|{.*?}|&.*?;|\s|\t|\n|\r|&nbsp;| ')
    s = p.sub('', response_content)
    return s


def main():
    while 1:
        start_true = start()
        if start_true:
            # 获取文本
            t1 = time.time()
            question_choice = get_word()
            print('get_word:', time.time() - t1)
            # 问题文本和选项文本
            question = question_choice[0]
            choices = question_choice[1:]
            # 搜索问题
            result = baidu_question(question)
            for i in choices:
                if i:
                    num = result.count(i)
                    print(i, ':', num)

if __name__ == '__main__':
    main()
